<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Ajax\Products\AmazonSkuAjax;
use App\Admin\Controllers\ErpController;
use App\Jobs\Products\AmazonSkuRelate;
use App\Models\Basics\SysPlatAccount;
use App\Models\Basics\AmazonCountry;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Illuminate\Support\Facades\DB;
class AmazonSkuController extends ErpController{

    protected $title = 'Amazon产品管理';

    protected $filters = [
        'amazon_sku' => null,
        'sku' => null,
        'classify_id' => null,
        'season' => null,
        'faneu_ex' => null,
        'country_id' => null,
        'seller_id' => null,
        'account_id' => null,
        'barcode_type' => null,
        'fan_eu' => null,
        'status' => null,
    ];

    protected function grid()
    {
        $filters = $this->getFilters();
        $this->initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->paginator($query);
        $action = $this->getAction();
        $filtersBlade = [];
        $filtersBlade['amazon_sku'] = $this->filters['amazon_sku'];
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $filtersBlade['season'] = getOptions(ProductClassify::$_season,$this->filters['season']);
        $filtersBlade['faneu_ex'] = getOptions([1 => '正常', 2 => '异常ALL', 3 => '异常1', 4 => '异常2&3'],$this->filters['faneu_ex']);
        $filtersBlade['country_id'] = getOptions(AmazonCountry::options(),$this->filters['country_id']);
        $filtersBlade['seller_id'] = getOptions(User::getSellerOptions(FALSE),$this->filters['seller_id']);
        $filtersBlade['account_id'] = getOptions(SysPlatAccount::options(),$this->filters['account_id']);
        $filtersBlade['fan_eu'] = getOptions(ProductAmazonSku::$_fanEu,$this->filters['fan_eu']);
        $filtersBlade['barcode_type'] = getOptions(ProductAmazonSku::$_barcodeType,$this->filters['barcode_type']);
        $filtersBlade['status'] = getOptions(ProductAmazonSku::$_status,$this->filters['status']);
        $downloadUrl = $this->getDownloadUrl('/xqc/products/amazon-sku-download');
        return view('products.amazon-sku.list.index', compact('paginator','action','filtersBlade','downloadUrl'));
    }

    private function _initQuery($filters){
        $query = ProductAmazonSku::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'amazon_sku'){
                $query->where(function ($query) use($filter){
                    $query->where('seller_sku', 'like', "%{$filter}%")
                        ->orWhere('parent_asin', 'like', "%{$filter}%")
                        ->orWhere('child_asin', 'like', "%{$filter}%")
                        ->orWhere('fnsku', 'like', "%{$filter}%");
                });
            }
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('classify_id', $filter);
                });
            }
            if($field == 'season'){
                $query->whereHas('skuClassify', function ($query) use($filter) {
                    $query->where('season',$filter);
                });
            }
            if($field == 'faneu_ex'){
                if($filter == 1){
                    $query->whereIn('times',[0,4]);
                }
                if($filter == 2){
                    $query->whereIn('times',[1,2,3]);
                }
                if($filter == 3){
                    $query->where('times',1);
                }
                if($filter == 4){
                    $query->whereIn('times',[2,3]);
                }
            }
            if(in_array($field,['country_id','seller_id','account_id','fan_eu','barcode_type','status'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    public function ajax(){
        $ajax = new AmazonSkuAjax();
        return $this->callAjax($ajax);
    }

    public function download(){
        $filters = $this->getFilters();
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['SKU','名称','季节性','品类','ModelNo','账号','国家','平台SKU','销售员',
            '条码类型','条码','PartNo.','平台PartNo.','母ASIN','子ASIN','FNSKU','泛欧模式','泛欧国家计数','创建人','创建时间','启用'];
        RExcel::exportCsv('Amazon产品',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = ProductAmazonSku::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    protected function form()
    {
        $form = new Form(new ProductAmazonSku());

        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
        });

        $form->hidden('id');
        $form->text('seller_sku','平台SKU')->rules('required')->required()->setWidth(5);

        //select联动----------
        $form->select('account_id', '账号')
            ->options(SysPlatAccount::options(['status' => 1]))
            ->required()
            ->load('country_id','/xqc/api-sys/products-country')->setWidth(5);
        $form->select('country_id', '国家')
            ->options(function (){
                $accountId = $this->account_id ?: old('account_id');
                $ac = DB::table('b_amazon_account_country as aac')
                    ->join('b_sys_country as c','c.id','=','aac.country_id')
                    ->where('aac.account_id',  $accountId)
                    ->pluck('c.country','c.id');
                if($ac->isNotEmpty()) {
                    return $ac->toArray();
                }else{
                    return [];
                }
            })->required()
            ->rules("required")->setWidth(5);
        //--------------

        $form->select('psku_id', 'SKU')
            ->options(function ($id) {
                $id = $id ?: old('psku_id');
                $ps = ProductSku::getModelById($id);
                if ($ps) {
                    return [$ps->id => $ps->psku_code];
                }else{
                    return [];
                }
            })->ajax('/xqc/api-sys/products-vague-sku')
            ->rules('required')->required()->setWidth(5);
        $form->select('barcode_type','条码类型')->options(ProductAmazonSku::$_barcodeType)->required()->rules("required")->setWidth(5);
        $form->text('barcode','条码')->rules('required_if:barcode_type,1,2',['required_if'=>'请录入条码'])->setWidth(5);
        $form->text('amazon_part_number','平台PartNo.')->setWidth(5);
        $form->text('parent_asin','母ASIN')->rules('required')->required()->setWidth(5);
        $form->text('child_asin','子ASIN')->rules('required')->required()->setWidth(5);
        $form->text('fnsku','FNSKU')->setWidth(5);
        $form->radio('fan_eu','是否泛欧')->options(ProductAmazonSku::$_fanEu)->default('0')->setWidth(5);

        if($form->isEditing()){
            $form->radio('status', '是否启用')->options(ProductAmazonSku::$_status)->default(1)->setWidth(5);
        }else{
            $form->hidden('status')->default(1);
        }

        $form->hidden('cuser_id')->value(Admin::user()->id);
        $form->hidden('seller_id');
        $form->hidden('times')->default(0);


        if($form->isCreating()){
            $form->disableCreatingCheck(false);
        }
        $form->saving(function (Form $form) {
            // 判断是否是新增操作
            if ($form->isCreating()) {

                if($form->barcode_type == 3){
                    $form->barcode = '无';
                }

                $count = ProductAmazonSku::query()
                    ->where('seller_sku',$form->seller_sku)
                    ->where('country_id',$form->country_id)
                    ->count();
                if($count > 0){
                    admin_error('重复添加','该平台SKU+国家已存在');
                    return back()->withInput();
                }
            }else{

                if($form->barcode_type == 3){
                    $form->barcode = '无';
                }
                if($form->status == 2){
                    $form->times = 0;
                }
                $count = ProductAmazonSku::query()
                    ->where('id','<>',$form->model()->id)
                    ->where('seller_sku',$form->seller_sku)
                    ->where('country_id',$form->country_id)
                    ->count();
                if($count > 0){
                    admin_error('重复添加','该平台SKU+国家已存在');
                    return back()->withInput();
                }

                /******(亚马逊Sku状态启用/停用) start********/
                //公司sku
                $sku = ProductSku::getModelById($form->psku_id);
                if(!$sku){
                    admin_error('ERROR', '公司产品SKU异常');
                    return back()->withInput();
                }
                //品类
                $classify = ProductClassify::getModelById($sku->classify_id);
                if(!$classify){
                    admin_error('ERROR', '品类异常');
                    return back()->withInput();
                }

                if ($form->status == ProductAmazonSku::STATUS_YES) {
                    //启用
                    //更新公司sku
                    if ($sku->status == ProductSku::STATUS_NO) {
                        $sku->status = ProductSku::STATUS_YES; //启用公司sku
                        $sku->save();
                    }

                    //更新品类
                    if ($classify->status == ProductClassify::SYNC_NO) {
                        $classify->status = ProductClassify::SYNC_YES; //启用品类
                        $classify->save();
                    }
                }else{
                    //停用
                    //更新公司sku
                    $amazonSkuCount = ProductAmazonSku::getProductAmazonSkuCount($form->id, $form->psku_id, ProductAmazonSku::STATUS_YES);
                    if ($amazonSkuCount == 0) {
                        $sku->status = ProductSku::STATUS_NO; //停用
                        $sku->save();
                    }

                    //更新品类
                    $skuCount = ProductSku::getClassifyProductSkuCount(null, $sku->classify_id, ProductSku::STATUS_YES);
                    if ($skuCount == 0) {
                        $classify->status = ProductClassify::SYNC_NO; //停用
                        $classify->save();
                    }
                }
                /*******end*******/

            }
        });
        $form->saved(function (Form $form) {
            //AmazonSKU关系
            AmazonSkuRelate::dispatch($form->model(),Admin::user()->id);
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
        });
        return $form;
    }
}
